package com.woniu.permissions.service.impl;

import cn.hutool.core.convert.impl.PeriodConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.exception.permissions.PermissionsException;
import com.woniu.exception.permissions.PermissionsExceptionCode;
import com.woniu.permissions.model.Resource;
import com.woniu.permissions.mapper.ResourceMapper;
import com.woniu.permissions.param.PageParam;
import com.woniu.permissions.param.UpdateResourceParam;
import com.woniu.permissions.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.nio.file.Watchable;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    /**
     * 新增资源
     * @param resourceName 资源名称
     * @return
     */
    @Override
    public Resource insertResource(String resourceName) {
        QueryWrapper<Resource> wrapper = new QueryWrapper<>();
        wrapper.eq("resource_name",resourceName);
        Resource resource = resourceMapper.selectOne(wrapper);
        if (resource!=null){
            throw new PermissionsException(PermissionsExceptionCode.PERMISSIONS_EXCEPTION_CODE_REPEAT);
        }
        resource.setResourceName(resourceName);
        resourceMapper.insert(resource);
        return resource;
    }

    /**
     * 根据id删除资源
     * @param id id
     * @return
     */
    @Override
    public Resource delResource(String id) {
        Resource resource = resourceMapper.selectById(id);
        if (resource==null){
            throw new PermissionsException(PermissionsExceptionCode.PERMISSIONS_EXCEPTION_CODE_NOT_CAN);
        }
        resourceMapper.deleteById(id);
        return resource;
    }

    /**
     * 根据id修改资源名
     * @param toBean
     * @return
     */
    @Override
    public Resource updateResourceById(UpdateResourceParam toBean) {
        Resource resource = resourceMapper.selectById(toBean.getId());
        if (resource==null){
            throw new PermissionsException(PermissionsExceptionCode.PERMISSIONS_EXCEPTION_CODE_NOT_CAN);
        }
        Resource resource1 = resource.setResourceName(toBean.getResourceName());
        return resource1;
    }
    /**
     * 分页查询所有资源
     * @param toBean 页码  每页个数
     * @return 返回查询出的page对象
     */
    @Override
    public Page<Resource> selPageResource(PageParam toBean) {
        Page<Resource> page = new Page<>(toBean.getPageNum(), toBean.getPageSize());
        resourceMapper.selectPage(page,null);
        return page;
    }
}
